#include "mysql.h"
#include <iostream>
#include <mysql/mysql.h>
#include <string>

Database::Database(const std::string& host, const std::string& user, const std::string& password, const std::string& database)
{
    conn = mysql_init(NULL);
    if (conn == NULL) 
    {
        std::cerr << "Error initializing MySQL connection" << std::endl;
    }

    if (mysql_real_connect(conn, host.c_str(), user.c_str(), password.c_str(), database.c_str(), 0, NULL, 0) == NULL) 
    {
        std::cerr << "Error connecting to database: " << mysql_error(conn) << std::endl;
    }
}

void Database::executeQuery(const std::string &query)
{
    if((mysql_query(conn, query.c_str()) != 0))
    {
        std::cerr<<"Error executing query:"<<mysql_error(conn)<<std::endl;
    }
    else
    {
        std::cout << "Query executed successfully" << std::endl;
    }

    MYSQL_RES *result = mysql_store_result(conn);
    if(result == NULL)
    {
        std::cerr<<"Error storing result set"<<std::endl;
        mysql_close(conn);
    }

    int num_fields = mysql_num_fields(result);
    MYSQL_ROW row;
    while(row = mysql_fetch_row(result))
    {
        for(int i = 0; i <num_fields; i++)
        {
            std::cout<<row[i]<<" ";
        }
        std::cout<<std::endl;
    }

    mysql_free_result(result);
    mysql_close(conn);
}

Database::~Database()
{
    mysql_close(conn);
}